<template>
  <div class="gtss-container">
    <!-- 添加加载状态 -->
    <div v-if="loading" class="loading-container">
      <i class="el-icon-loading"></i>
      加载中...
    </div>

    <!-- 添加空状态 -->
    <div v-else-if="!gtssData || Object.keys(gtssData).length === 0" class="empty-container">
      <el-empty description="暂无毕设数据">
        <el-button type="primary" @click="refreshData">刷新数据</el-button>
      </el-empty>
    </div>

    <!-- 模块导航 -->
    <div class="module-buttons">
      <el-button
        v-for="module in modules"
        :key="module.value"
        :type="activeModule === module.value ? 'primary' : ''"
        :disabled="!isModuleAccessible(module.value)"
        @click="activeModule = module.value"
      >
        {{ module.label }}
      </el-button>
    </div>

    <!-- 信息卡片 -->
    <el-card class="info-card">
      <!-- 标题区域 -->
      <div class="card-header">
        <h3>{{ activeModuleLabel }} {{ showDownload ? '（下载）' : '' }}</h3>
        <!-- 下载按钮 -->
        <el-button
          v-if="showDownload"
          type="primary"
          icon="el-icon-download"
          @click="handleDownload"
        >
          下载文档
        </el-button>
      </div>

      <!-- 信息展示 -->
      <div class="info-content">
        <el-descriptions :column="2" border>
          <!-- 左侧信息 -->
          <el-descriptions-item label="题目名称">{{ gtssData.title }}</el-descriptions-item>
          <el-descriptions-item label="题目来源">{{ gtssData.source }}</el-descriptions-item>
          <el-descriptions-item label="题目类型">{{ gtssData.type }}</el-descriptions-item>
          <el-descriptions-item label="指导教师">{{  gtssData.teacher_realname }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ gtssData.status }}</el-descriptions-item>

          <!-- 右侧信息 -->
          <el-descriptions-item label="学号">{{ userInfo.userid }}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{ userInfo.realname }}</el-descriptions-item>
          <el-descriptions-item label="院系">{{ userInfo.college }}</el-descriptions-item>
          <el-descriptions-item label="专业">{{ userInfo.major }}</el-descriptions-item>
          <el-descriptions-item label="提交日期">{{ gtssData.submit_date }}</el-descriptions-item>
        </el-descriptions>

        <!-- 审核记录 -->
        <div class="audit-section">
          <h4>审核记录</h4>
          <el-table :data="auditRecords" style="width: 100%">
            <el-table-column prop="auditTime" label="审核时间"></el-table-column>
            <el-table-column prop="auditor" label="审核人"></el-table-column>
            <el-table-column prop="result" label="审核结果"></el-table-column>
            <el-table-column prop="remark" label="审核备注"></el-table-column>
          </el-table>
        </div>

        <!-- 文件上传及提交区域 -->
        <div class="submit-section" v-if="showSubmit && !isFileUploaded">
          <el-upload
            class="upload-demo"
            :action="uploadAction"
            :auto-upload="false"
            :on-change="handleFileChange"
            :show-file-list="false"
          >
            <el-button type="primary">选择文件</el-button>
            <span v-if="file" class="file-tip">已选择文件：{{ file.name }}</span>
          </el-upload>

          <el-button
            type="primary"
            :loading="submitting"
            @click="handleSubmit"
            :disabled="!file"
          >
            {{ submitting ? '提交中...' : '提交审核' }}
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading: true,
      moduleCategoryMap: {
        task: '任务书',
        proposal: '开题报告',
        midterm: '中期报告',
        defense: '答辩材料',
        final: '结题报告'
      },
      modules: [
        { label: '选题', value: 'selection' },
        { label: '任务书', value: 'task' },
        { label: '开题报告', value: 'proposal' },
        { label: '中期报告', value: 'midterm' },
        { label: '答辩', value: 'defense' },
        { label: '结束', value: 'final' }
      ],
      activeModule: 'selection',
      userInfo: {
        userid: localStorage.getItem('userid'),
        realname: localStorage.getItem('realname'),
        college: '',
        major: ''
      },
      gtssData: {},
      topicData: {},
      teacherInfo: {},
      auditRecords: [],
      submitting: false,
      file: null,
      isFileUploaded: false,// 文件上传状态
      userFiles: [],// 用户已上传文件列表
      // 模块顺序映射
      moduleOrder: {
        selection: 1,
        task: 2,
        proposal: 3,
        midterm: 4,
        defense: 5,
        final: 6
      },

      // 模块状态映射
      moduleStatusMap: {
        selection: '选题',
        task: '任务书',
        proposal: '开题报告',
        midterm: '中期报告',
        defense: '答辩',
        final: '结束'
      },
    };
  },
  computed: {
    isModuleAccessible() {
      return (moduleValue) => {
        // 管理员和教师可以访问所有模块
        const role = localStorage.getItem('role');
        if (role === '教师' || role === '管理员' || role === '超级管理员') {
          return true;
        }
        if (!this.gtssData || !this.gtssData.status) return false;

        // 学生只能访问当前进度及之前的模块
        if (!this.gtssData.status) return false;

        // 直接使用 progress_order 属性
        const currentProgress = this.gtssData.progress_order || 0;
        const moduleProgress = this.moduleOrder[moduleValue] || 0;

        return moduleProgress <= currentProgress;
      };
    },
    uploadAction() {
      return `${this.$axios.defaults.baseURL}/file-template/upload`;
    },
    activeModuleLabel() {
      return this.modules.find(m => m.value === this.activeModule).label
    },
    showDownload() {
      // 添加安全检查
      return this.gtssData && this.gtssData.status === '已通过';
    },
    showSubmit() {
      // 添加安全检查
      if (!this.gtssData || !this.gtssData.status) return false;

      const role = localStorage.getItem('role');
      const currentStatus = this.gtssData.status;
      const currentModule = this.activeModule;

      // 调试信息
      console.log('showSubmit 计算中:', {
        role,
        currentStatus,
        currentModule,
        isFileUploaded: this.isFileUploaded
      });

      // 1. 管理员和教师不受限制
      if (role === '教师' || role === '管理员' || role === '超级管理员') {
        const validModules = ['task', 'proposal', 'midterm', 'defense', 'final'];

        // 确保当前模块是有效模块
        if (!validModules.includes(currentModule)) return false;

        // 总是显示上传区域（无论文件是否已上传）
        return true;
      }

      // 2. 学生逻辑
      const currentModuleStatus = this.moduleStatusMap[currentModule];
      const validStatuses = ['待提交', '审核驳回'];

      // 检查当前模块是否匹配毕设状态
      if (currentModuleStatus !== currentStatus) {
        return false;
      }

      // 检查状态是否在有效状态中
      if (!validStatuses.includes(currentStatus)) {
        return false;
      }

      // 如果是审核驳回状态，总是显示上传区域
      if (currentStatus === '审核驳回') {
        return true;
      }

      // 待提交状态，且文件未上传（审核通过），则显示
      return !this.isFileUploaded;
    }
  },
  async mounted() {
    this.loading = true;
    try {
      await this.fetchUserDetails();
      await this.fetchGtssData();
      await this.fetchTopicData();
      this.parseAuditRecords();
      await this.fetchUserFiles();
      this.checkFileUploadStatus();
    } catch (error) {
      console.error('初始化失败', error);
    } finally {
      this.loading = false;
    }
  },
  watch: {
    activeModule() {
      this.file = null; // 切换模块时清空已选文件
      this.checkFileUploadStatus(); // 检查新模块的文件上传状态
    }
  },
  methods: {
    // 获取用户已上传文件列表
    async fetchUserFiles() {
      try {
        const userId = this.userInfo.userid;
        // 修改为调用新的接口路径
        const res = await this.$axios.get(`/file-template/listByUploader?uploaderid=${userId}`);
        if (res.data && res.data.state === 'success') {
          this.userFiles = res.data.data || [];
        }
      } catch (error) {
        console.error('获取用户文件失败', error);
        this.userFiles = [];
      }
    },

    // 检查当前模块文件是否已上传
    checkFileUploadStatus() {
      if (this.activeModule === 'selection') {
        this.isFileUploaded = false;
        return;
      }

      // 获取当前模块对应的文件分类
      const category = this.moduleCategoryMap[this.activeModule];
      if (!category) {
        this.isFileUploaded = false;
        return;
      }

      console.log('当前模块:', this.activeModule);
      console.log('需要的分类:', category);
      console.log('用户文件列表:', this.userFiles);

      // 检查是否有匹配的文件
      this.isFileUploaded = this.userFiles.some(file => {
        // 添加详细的调试信息
        const match = file.category === category &&
          file.filePurpose === '学生提交' &&
          (file.status === '审核通过' || file.status === '待审核');

        console.log(`文件检查: ${file.filename}`, {
          categoryMatch: file.category === category,
          purposeMatch: file.filePurpose === '学生提交',
          statusMatch:file.status === '审核通过' || file.status === '待审核',
          overallMatch: match
        });

        return match;
      });

      console.log('文件上传状态:', this.isFileUploaded);
    },



    // 文件选择处理
    handleFileChange(file) {
      this.file = file.raw;
      return false;
    },

    async fetchUserDetails() {
      try {
        const res = await this.$axios.get(`/user/info?userid=${this.userInfo.userid}`);
        // 确保绑定到正确的数据结构
        this.userInfo = {
          ...this.userInfo,
          college: res.data.data.college,
          major: res.data.data.major
        };
      } catch (error) {
        console.error('获取用户信息失败', error);
      }
    },

    async fetchGtssData() {
      try {
        const res = await this.$axios.get(`/gtss/list?userId=${this.userInfo.userid}`);

        console.log('后端返回的数据:', res.data);

        // 处理后端返回 null 的情况
        if (res.data === null || res.data.data === null) {
          this.gtssData = {};
          console.warn('后端返回的毕设数据为 null');
          return;
        }

        // 根据后端返回的实际结构进行调整
        if (res.data && res.data.state === 'success') {
          this.gtssData = res.data.data || {};
        } else if (res.data && res.data.data) {
          this.gtssData = res.data.data;
        } else {
          this.gtssData = res.data || {};
        }

        // 确保有基础结构
        if (!this.gtssData.teacher_audit) this.gtssData.teacher_audit = [];
        if (!this.gtssData.admin_audit) this.gtssData.admin_audit = [];

        console.log('gtssData:', this.gtssData);

      } catch (error) {
        console.error('获取毕设信息失败', error);
        this.gtssData = {};
      }
    },

    async fetchTopicData() {
      if (!this.gtssData || !this.gtssData.topic_id) return;
      try {
        const res = await this.$axios.get(`/topic/${this.gtssData.topic_id}`)
        this.topicData = res.data
        this.fetchTeacherInfo(res.data.submitter_id)
      } catch (error) {
        console.error('获取课题信息失败', error)
      }
    },

    async fetchTeacherInfo(teacherId) {
      try {
        const res = await this.$axios.get(`/user/info?userid=${teacherId}`)
        this.teacherInfo = res.data
      } catch (error) {
        console.error('获取教师信息失败', error)
      }
    },

    parseAuditRecords() {
      this.auditRecords = [
        ...(this.gtssData.teacher_audit || []).map(a => ({
          auditTime: a.auditTime,
          auditor: this.teacherInfo.realname,  // 直接使用教师信息
          result: a.result,
          remark: a.remark
        })),
        ...(this.gtssData.admin_audit || []).map(a => ({
          auditTime: a.auditTime,
          auditor: '管理员',
          result: a.result,
          remark: a.remark
        }))
      ];
    },

    handleDownload() {
      // 根据当前模块调用下载接口
      this.$axios.get(`/file-template/download?type=${this.activeModule}`)
        .then(() => {
          this.$message.success('开始下载文件')
        })
        .catch(() => {
          this.$message.error('下载失败')
        })
    },

    async handleSubmit() {
      try {
        const formData = new FormData();
        formData.append('file', this.file);
        formData.append('userId', this.userInfo.userid);
        formData.append('moduleType', this.activeModule);

        await this.$axios.post('/file-template/student-upload', formData);

        this.$message.success('提交成功');
        this.file = null; // 清空已选文件
        await this.fetchGtssData(); // 刷新数据
        await this.fetchUserFiles();
        this.checkFileUploadStatus();
      } catch (error) {
        this.$message.error('提交失败');
      }
    }
  }
}
</script>

<style scoped>
.submit-section {
  margin-top: 30px;
  display: flex;
  align-items: center;
  gap: 20px;
}
.file-tip {
  margin-left: 10px;
  color: #666;
  font-size: 14px;
}

.upload-demo {
  display: flex;
  align-items: center;
}
.gtss-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.module-buttons {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.info-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.audit-section {
  margin-top: 30px;
}

.submit-btn {
  margin-top: 30px;
  text-align: center;
}

.el-descriptions {
  margin-top: 20px;
}
</style>
